package top.zhangjianyong.blog.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Collection;
import java.util.List;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.zhangjianyong.blog.entity.po.BlogTag;
import top.zhangjianyong.blog.mapper.BlogTagMapper;
import top.zhangjianyong.blog.record.DelAndAdd;
import top.zhangjianyong.blog.service.BlogTagService;
import top.zhangjianyong.blog.utils.EntityUtil;

/**
 * 博客标签
 *
 * @author zhangjianyong
 * @since 2024/8/3 上午10:17
 */
@Service
public class BlogTagServiceImpl extends ServiceImpl<BlogTagMapper, BlogTag>
    implements BlogTagService {

  private final BlogTagService blogTagService;

  public BlogTagServiceImpl(@Lazy BlogTagService blogTagService) {
    this.blogTagService = blogTagService;
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public boolean saveBatch(Long blogId, List<Long> tagIds) {
    if (CollectionUtil.isEmpty(tagIds)) return true;
    // 找出已存在的tag
    List<BlogTag> list =
        lambdaQuery().select(BlogTag::getTagId).eq(BlogTag::getBlogId, blogId).list();
    List<Long> oldTags = list.stream().map(BlogTag::getTagId).toList();
    // 获取删除和新增tag
    DelAndAdd<Long> delAndAdd = EntityUtil.getDelAndAdd(oldTags, tagIds);
    // 处理删除和新增
    Collection<Long> del = delAndAdd.del();
    boolean removeFlag =
        CollectionUtil.isEmpty(del)
            || lambdaUpdate().eq(BlogTag::getBlogId, blogId).in(BlogTag::getTagId, del).remove();

    List<BlogTag> saveBlogTag =
        delAndAdd.add().stream()
            .map(
                tagId -> {
                  BlogTag blogTag = new BlogTag();
                  blogTag.setTagId(tagId);
                  blogTag.setBlogId(blogId);
                  return blogTag;
                })
            .toList();

    boolean saveFlag = CollectionUtil.isEmpty(saveBlogTag) || blogTagService.saveBatch(saveBlogTag);
    return saveFlag && removeFlag;
  }

  @Override
  public void removeByTag(Long tagId) {
    lambdaUpdate().eq(BlogTag::getTagId, tagId).remove();
  }

  @Override
  public void removeByBlog(Long blogId) {
    lambdaUpdate().eq(BlogTag::getBlogId, blogId).remove();
  }
}
